import { defineStore, acceptHMRUpdate } from "pinia";
import { systemAppStore } from "./system";
import Axios from "axios";
import PsMessageBox from "@/components/message-box";
import { logout } from "@/api/login";
import { getMemberInfo, checkStatus, getUserTsb } from "@/api/user";
import { userRightById, migratePackages } from "@/api/rights";
import { kefuUrl } from "@/utils/costum";
import { getRightIdByType } from "@/utils/userRights";
import type { RIGHT_IDS } from "@/utils/userRights";
import { invokeAPi, invokeAsyncAPi } from "@/xz-fn";
interface RIGHTS_LEFT {
  WORD?: any;
  SCREENSHOT?: any;
  DICT?: any;
  ONLINE?: any;
  PDF?: any;
  PLAY?: any;
}
export const userAppStore = defineStore({
  id: "user",
  state: () => ({
    token: "",
    hasLogin: false,
    userInfo: {} as any,
    anonymousId: "",
    userTsbCount: 0, // 用户翻译币
    rightsLeft: {} as any,
    confirm: false
  }),
  actions: {
    getToken() {
      return invokeAsyncAPi("fq_GetLoginToken")
        .then((token: any) => {
          this.token = token;
        });
    },
    setToken(token: string) {
      this.token = token;
    },
    setLoginState(val: boolean) {
      this.hasLogin = val;
    },
    checkStatus() {
      return new Promise<void>((resolve, reject) => {
        checkStatus()
          .then(() => {
            this.hasLogin = true;
            resolve();
          })
          .catch((e: any) => {
            this.hasLogin = false;
            reject(e);
          });
      });
    },
    /**
     * 获取用户基础信息
     * @param {boolean} runSourceData 是否返回会员信息源数据
     * @param {boolean} isMigratePkg 是否操作迁移权益包
     */
    getUserInfo(runSourceData: boolean = false, isMigratePkg: boolean = false, noSet: boolean = false) {
      return new Promise((resolve, reject) => {
        Axios.all([
          getMemberInfo()
        ])
          .then(
            Axios.spread(async (res1) => {
              if (isMigratePkg) {
                const newRes1 = await this.migrateRightPackages(res1?.data?.buy_right_package).catch(() => null)
                if (newRes1) {
                  // 存在 newRes1 说明权益包迁移成功
                  invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
                    "action": "member-change",
                    "data": { type: "migrate-right-success", info: newRes1.data }
                  }))
                  invokeAPi('fq_update_member_info', JSON.stringify(newRes1));

                  res1 = newRes1
                }
              }
              let sourceData
              const data = res1.data || {};
              
              if(runSourceData){
                sourceData = JSON.parse(JSON.stringify(res1))
              } 
              
              !noSet && this.setUserInfo(data);
              resolve(sourceData || data);
            })
          )
          .catch((e) => {
            reject(e);
          });
      });
    },
    resetUserInfo(isCallXZ = true) {
      this.hasLogin = false;
      this.token = "";
      this.userInfo = {};
      this.userTsbCount = 0;
      if (isCallXZ) {
        invokeAPi("xz_exit");
      }
      PsMessageBox.close();
    },
    login() {
      invokeAPi('fq_ShowLogin')
    },
    /**
     * 合并用户基础信息
     */
    mergeUserInfo(data = {}, isCallXZ: boolean = true) {
      this.userInfo = Object.assign({}, this.userInfo, data);
      isCallXZ && invokeAPi(
        "xz_update_user_info",
        JSON.stringify({
          username: (this.userInfo as any).Nickname,
          headimgurl: (this.userInfo as any).Portrait
        })
      );
    },
    /**
     * 设置用户信息
     */
    setUserInfo(data: any = {}) {
      data.buy_right_package = (data.buy_right_package || []).filter(
        (item: { pkg_id: string }) => {
          return systemAppStore().appInfo.allPackages.some(
            (pkg_id: string) => item.pkg_id === pkg_id
          );
        }
      );
      data.is_member = data.buy_right_package.some(
        (item: {
          unlimited: boolean;
          expire_at: string | number | Date;
        }) =>
          item.unlimited ||
          new Date(item.expire_at).getTime() / 1000 > data.server_time
      );
      data.has_buy = data.buy_right_package.some(
        (it: { has_buy: boolean }) => it.has_buy
      );

      console.log('userInfo：', data)
      this.userInfo = data;
    },
    /**
     * 检查并迁移权益包
     */
    async migrateRightPackages(list: any[] = []) {
      const isHasOldPackages = (list || []).some(
        (item: { pkg_id: string }) => {
          return import.meta.env.VITE_APP_PKGID_OLD === item.pkg_id;
        }
      );
      if(!isHasOldPackages) return

      const res: any = await migratePackages({
        pkg_id: import.meta.env.VITE_APP_PKGID_OLD
      }).catch(() => {})

      if(res?.data?.sub_code === 'ok'){
        return this.getUserInfo(true, false, true)
      }
    },
    /**
     * 打开登录窗口
     */
    openLogin() {
      invokeAPi("fq_ShowLogin");
    },
    /**
     * 退出登录
     */
    logout() {
      return logout({ uuid: systemAppStore().appInfo.uuid }).then(() => {
        this.resetUserInfo();
      });
    },
    setCustomerConfirm(message: string) {
      if (!this.confirm) {
        this.confirm = true;
        setTimeout(() => {
          PsMessageBox({
            dangerouslyUseHTMLString: true,
            message: message,
            confirmButtonText: "联系客服",
            iconClass: "error",
            center: true,
            beforeClose: (action: string, _instance: any, done: any) => {
              if (action === "confirm") {
                window.open(kefuUrl);
              } else {
                this.confirm = false;
                done();
              }
            }
          });
        }, 50);
      }
    },
    setLogoutConfirm(message: string) {
      if (!this.confirm) {
        this.confirm = true;
        setTimeout(() => {
          PsMessageBox({
            message,
            iconClass: "error"
          })
            .then(() => {
              this.openLogin();
            })
            .finally(() => {
              this.confirm = false;
            });
        }, 50);
      }
    },
    setAnonymousId(id: string) {
      this.anonymousId = id;
    },
    async getRightsLeft(
      translateType: keyof RIGHT_IDS,
      { isCache = true } = {}
    ) {
      if (isCache && this.rightsLeft[translateType]) {
        return this.rightsLeft[translateType];
      }
      const right_id = getRightIdByType(translateType);
      return userRightById({
        right_id
      }).then((res: { data: any }) => {
        // 会员状态不一致，获取最新的
        if (res.data.is_vip !== (this.userInfo.is_member || false)) {
          this.getUserInfo()
        }

        this.rightsLeft[translateType] = res.data;
        return res;
      });
    },
    /**
     * 获取用户翻译币
     */
    async getTsbCount() {
      if (!this.hasLogin) {
        this.userTsbCount = 0;
        return 0;
      }
      return new Promise((resolve, reject) => {
        getUserTsb({
          unit_id: "tsb"
        })
          .then((res: any) => {
            const { count } = res?.data || {};
            this.userTsbCount = count || 0;
            resolve(res);
          })
          .catch(reject);
      });
    },
    /**
     * 消费
     * @param {String} funType 功能权益类型
     * @param {String} engine 引擎
     */
    async rightConsume(rightType: keyof RIGHT_IDS, engine: string) {
      if (engine) {
        if (this.hasLogin) {
          await this.getTsbCount();
          invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
            "action": "tsb-change",
            "data": { type: "consume", count: this.userTsbCount }
          }))
        }
        return;
      }
      await this.getRightsLeft(rightType, { isCache: false });
      invokeAPi("fq_NotifyWebMessageEx", "", JSON.stringify({
        "action": "right-change",
        "data": { type: "consume", right: this.rightsLeft[rightType] }
      }))
    },
    setTsbCount(val: number) {
      this.userTsbCount = val || 0;
    }
  }
});
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(userAppStore, import.meta.hot));
}
